package com.common.zrd.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * author: zrd
 * @Date: 2019/11/6 11:33
 * @Description:公共日志工具类
 */
public class CommonLogEntries {
    private static ToString toString = null;

    static {
        try {
            toString = new FastJson();
        } catch (Throwable e) {
            try {
                toString = new FastxmlJackson();
            } catch (Throwable localThrowable1) {
            }
        }
    }

    private Map<String, Object> data = new HashMap(0);

    public static CommonLogEntries createEntries() {
        return new CommonLogEntries();
    }

    public static CommonLogEntries createEntries(Object value) {
        return createEntries("root", value);
    }

    public static CommonLogEntries createEntries(String key, Object value) {
        return createEntries().bind(key, value);
    }

    public CommonLogEntries bind(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public CommonLogEntries unbind(String key) {
        this.data.remove(key);
        return this;
    }

    @Override
    public String toString() {
        if (toString != null) {
            try {
                return toString.toString(this.data);
            } catch (Throwable localThrowable) {
            }
        }
        return this.data.toString();
    }
/**
 * 描述：  
 * 备注： 
 * 日期： 11:35 2020/4/8
 * 作者： zrd
 * @return
 **/
    private interface ToString {
        String toString(Object paramObject);
    }

    private static class FastJson
            implements CommonLogEntries.ToString {
        FastJson() {
            new JSONObject();
        }

        @Override
        public String toString(Object data) {
            return JSON.toJSONString(data);
        }
    }

    private static class FastxmlJackson
            extends ObjectMapper
            implements CommonLogEntries.ToString {
        private static final long serialVersionUID = 2446343702057724438L;

        FastxmlJackson() {
            setSerializationInclusion(JsonInclude.Include.NON_NULL);
        }

        @Override
        public String toString(Object data) {
            try {
                return writeValueAsString(data);
            } catch (Throwable e) {
            }
            return String.valueOf(data);
        }
    }
}
